import React, { Component } from 'react'
import axios from 'axios'

import store from '../../../redux'
import Api from '../../../config/api'

import Navbar from '../../../Component/navbar'
import Com from '../../../common/common'

import Button from 'antd/lib/button'
import Table from 'antd/lib/table'
import Form from 'antd/lib/form'
import Input from 'antd/lib/input'
import Spin from 'antd/lib/spin'
import Icon from 'antd/lib/icon'
import DatePicker from 'antd/lib/date-picker'
import Modal from 'antd/lib/modal'

import moment from 'moment';
import 'moment/locale/zh-cn';
moment.locale('zh-cn');

const FormItem = Form.Item;
const antIcon = <Icon type="loading" style={{ fontSize: 24, marginTop: 200 }} spin />;

let oper = null;

function formatDay(value) {
    if (parseInt(value, 10) < 10) {
        return '0' + value;
    }
    else {
        return value
    }
}

function getToday() {
    let now = new Date();
    let day, month, year;
    day = now.getDate();
    month = now.getMonth() + 1;
    year = now.getFullYear();
    return year + '-' + formatDay(month) + '-' + formatDay(day);
}

class OperBar extends Component {
    constructor(props) {
        super(props);
        this.state = {
            startDate: getToday(),
            endDate: '',
            startMonent: null,
            endMoment: null,
        }
    }
    componentDidMount() {
        this.search();
        this.setState({
            startMoment: moment(getToday(), "YYYY-MM-DD")
        })
    }
    getTime(type, moment, time) {
        if (type === 'start') {
            this.setState({
                startDate: time,
                startMoment: moment
            })
        }
        else {
            this.setState({
                endDate: time,
                endMoment: moment
            })
        }
    }
    disabledstartTime(current) {
        if (this.state.endMoment) {
            return current > this.state.endMoment
        }
        else {
            return false
        }
    }
    disabledendTime(current) {
        if (this.state.startMoment) {
            return current < this.state.startMoment
        }
        else {
            return false
        }
    }
    search() {
        let obj = {
            account: this.accountInput.input.value,
            startTime: this.state.startDate,
            endTime: this.state.endDate
        }
        this.props.search(obj)
    }
    render() {
        return (
            <Navbar ref={(item) => { oper = item }}>
                <Form layout="inline">
                    <FormItem label="账号"><Input style={{ width: '200px' }} ref={(input) => { this.accountInput = input }} /></FormItem>
                    <FormItem label="开始时间">
                        <DatePicker format="YYYY-MM-DD" defaultValue={moment(this.state.startDate, "YYYY-MM-DD")} disabledDate={this.disabledstartTime.bind(this)} onChange={this.getTime.bind(this, 'start')} />
                    </FormItem>
                    <FormItem label="结束时间">
                        <DatePicker format="YYYY-MM-DD" disabledDate={this.disabledendTime.bind(this)} onChange={this.getTime.bind(this, 'end')} />
                    </FormItem>
                    <FormItem>
                        <Button type="primary" icon="search" onClick={this.search.bind(this)}>查询</Button>
                    </FormItem>
                </Form>
            </Navbar>
        )
    }
}

class Table1 extends Component {
    constructor(props) {
        super(props)
        this.state = {
            dataNum: 0,
            tableHeight: 300,
            tableData: this.props.tableData,
            currentPage: 1,
            billModal: false,
            chargingType: [],
            bill: {},
            nowModalData: {},
            msgTotal: 0
        }
    }
    async componentDidMount() {
        await Com.getSelection.call(this, 'SmsGatewayChargingTypeEnum', 'chargingType', false);
        setTimeout(() => {
            let operbarHeight = oper.box.offsetHeight + 10 + 10;
            this.setState({
                tableHeight: store.getState().mainTableSize - operbarHeight - 45 - 33 - 71 - 15 - 30
            })
            this.unscribe = store.subscribe(this.fullTable.bind(this))
        }, 100)
    }
    componentWillReceiveProps(nextProps) {
        this.setState({
            tableData: nextProps.tableData,
            dataNum: nextProps.dataNum,
            currntPage: nextProps.currentPage
        })
    }
    componentWillUnmount() {
        this.unscribe()
    }
    fullTable() {
        let operbarHeight = oper.box.offsetHeight + 10 + 10;
        this.setState({
            tableHeight: store.getState().mainTableSize - operbarHeight - 45 - 33 - 71 - 15 - 30
        })
    }
    openBill(row) {
        this.setState({
            nowModalData: {
                account: row.account,
                day: row.day
            }
        })
        const param = `account=${row.account}&date=${row.day}`
        axios.post(Api['getDayBillDetail'], param).then((res) => {
            if (res) {
                const obj = {
                    list: res.data.list,
                    sum: res.data.sumPrice
                }
                let total = 0;
                obj.list.forEach((item, index) => {
                    item.key = index
                    total += parseInt(item.msgCount,10);
                    this.state.chargingType.forEach(item2 => {
                        // eslint-disable-next-line
                        if (item2.index == item.chargingType) {
                            item.typeName = item2.desc
                        }
                    })
                })
                this.setState({
                    bill: obj,
                    msgTotal: total
                }, () => {
                    this.setState({
                        billModal: true
                    })
                })
            } 
        })
    }
    billCancel() {
        this.setState({
            billModal: false
        })
    }
    render() {
        const columns = [
            { title: '时间', dataIndex: 'day', key: '1', width: 150 },
            { title: '账号', dataIndex: 'account', key: '2', width: 200 },
            { title: '业务名称', dataIndex: 'companyName', key: '8', width: 300 },
            { title: '发送总数', dataIndex: 'msgCount', key: '3', width: 150 },
            {
                title: '成功数', key: '4', width: 150, render: (record) => {
                    return <span style={{ color: 'green' }}>{record.successCount}</span>
                }
            },
            {
                title: '失败数', key: '5', width: 150, render: (record) => {
                    return <span style={{ color: 'red' }}>{record.failureCount}</span>
                }
            },
            { title: '未知数', dataIndex: 'unknownCount', key: '6', width: 220 },
            {
                title: '成功率', key: '7', widht: 150, render: (record) => {
                    return <span style={{ color: '#104E8B' }}>{record.successRate}</span>
                }
            },
            {
                title: '操作',
                key: '9',
                width: 100,
                fixed: 'right',
                render: (record) => {
                    return (
                        <div>
                            <a onClick={this.openBill.bind(this, record)}>账单明细</a>
                        </div>
                    )
                }
            }
        ];
        const col2 = [
            { title: "通道", dataIndex: "name", key: "1", width: 200 },
            { title: "计费方式", dataIndex: "typeName", key: "5", width: 200 },
            { title: "发送总数", dataIndex: "msgCount", key: "2", width: 200 },
            { title: "单价", dataIndex: "price", key: "3", width: 200 },
            { title: "消费金额", dataIndex: "totalPrice", key: "4", width: 200 },

        ]
        return (
            <div className="common-table">
                <Table title={(data) => { return '客户日发送统计' }} columns={columns} dataSource={this.state.tableData} pagination={{
                    onChange: this.props.changePage,
                    onShowSizeChange: this.props.changePageSize,
                    defaultPageSize: 20,
                    pageSizeOptions: ['20', '50', '100'],
                    showSizeChanger: true,
                    showQuickJumper: true,
                    current: this.state.currntPage,
                    total: this.state.dataNum,
                    showTotal: total => `共 ${total} 条数据`
                }} scroll={{ x: 1950, y: this.state.tableHeight }}></Table>
                <Modal width={800} visible={this.state.billModal} onCancel={this.billCancel.bind(this)} title={"账单明细 - " + this.state.nowModalData.account + "(" + this.state.nowModalData.day + ")"} footer={[
                    <Button key="cancel" type="danger" onClick={this.billCancel.bind(this)}>取消</Button>
                ]} >
                    <Table
                        columns={col2}
                        dataSource={this.state.bill.list}
                        pagination={false}
                    />
                    <div style={{ marginTop: '10px', float: 'right' }}>
                        <h3>总计条数：{this.state.msgTotal}</h3>
                        <h3>总计金额：{this.state.bill.sum}</h3>
                    </div>
                </Modal>
            </div>
        )
    }
}

class Box extends Component {
    constructor(props) {
        super(props)
        this.state = {
            loading: true,
            tableData: [],
            searchParams: {},
            totalNum: 0,
            paginationData: {
                current: 1,
                pageNum: 1,
                pageSize: 20
            },
            currentPage: 1,
        }
    }
    setParams(obj) {
        this.setState({
            searchParams: obj
        }, () => {
            this.search('btn');
        })
    }
    search(type) {
        let data = JSON.parse(JSON.stringify(this.state.searchParams));
        if (type === 'btn') {
            data.pageNum = 1;
            this.setState({
                currentPage: 1
            })
        } else {
            data.pageNum = this.state.paginationData.pageNum;
        }
        data.pageSize = this.state.paginationData.pageSize;
        this.setState({
            loading: true,
        })
        axios.post(Api['queryCustomDayStatistic'], data).then((res) => {
            if (res) {
                let data = JSON.parse(JSON.stringify(res.data));
                data.list.forEach((item, index) => { item.key = index; })
                this.setState({
                    loading: false,
                    tableData: data.list,
                    totalNum: data.total
                })
            }
        }).catch((error) => {
            console.log(error)
        })
    }
    changePageSize(current, size) {
        let pagination = JSON.parse(JSON.stringify(this.state.paginationData))
        pagination.pageNum = current;
        pagination.pageSize = size;
        this.setState({
            paginationData: pagination,
            currentPage: current
        }, () => { this.search('pag') })
    }
    changePage(pageNum, pageSize) {
        let pagination = JSON.parse(JSON.stringify(this.state.paginationData))
        pagination.pageNum = pageNum;
        pagination.pageSize = pageSize;
        this.setState({
            paginationData: pagination,
            currentPage: pageNum
        }, () => { this.search('pag') })
    }
    render() {
        return (
            <div>
                <OperBar search={this.setParams.bind(this)} />
                <Spin spinning={this.state.loading} indicator={antIcon}>
                    <Table1 currentPage={this.state.currentPage} tableData={this.state.tableData} dataNum={this.state.totalNum} changePageSize={this.changePageSize.bind(this)} changePage={this.changePage.bind(this)} />
                </Spin>
            </div>
        )
    }
}

export default Box